package handlers

import (
	"bookshelf/cache"
	"bookshelf/moders"
	"bookshelf/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "redis_key_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误三次",
		})
		return
	}
	var user moders.User
	err := moders.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "密码错误三次，封禁俩小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
